﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Simple.CMS.Core;
using Simple.CMS.Entities;

namespace Simple.CMS.Web.Repository
{
    public class CmsContext : DbContext
    {
        public CmsContext(DbContextOptions<CmsContext> options) : base(options)
        {

        }

        /// <summary>
        /// 管理员
        /// </summary>
        public DbSet<AdminUser> AdminUsers { get; set; }

        /// <summary>
        /// 文章
        /// </summary>
        public DbSet<Article> Articles { get; set; }

        /// <summary>
        /// 横幅
        /// </summary>
        public DbSet<Banner> Banners { get; set; }



        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            ModelBuild(modelBuilder.Entity<Article>()).ToTable("Article");

            ModelBuild(modelBuilder.Entity<Banner>()).ToTable("Banner");

            ModelBuild(modelBuilder.Entity<AdminUser>()).ToTable("AdminUser");

        }

        private EntityTypeBuilder<TEntity> ModelBuild<TEntity>(EntityTypeBuilder<TEntity> entityTypeBuilder) where TEntity : EntityBase
        {
            entityTypeBuilder.HasKey(it => it.Id);
            entityTypeBuilder.Property(it => it.Id).ValueGeneratedOnAdd();//自增

            entityTypeBuilder.Property(it => it.CreateTime).HasDefaultValue(DateTime.Now).ValueGeneratedOnAddOrUpdate();
            //entityTypeBuilder.Property(it => it.CreateTime).HasValueGenerator();//.HasDefaultValue(DateTime.Now);            

            entityTypeBuilder.Property(it => it.LastUpDateTime).HasDefaultValue(DateTime.Now).ValueGeneratedOnAddOrUpdate();
            //entityTypeBuilder.Property(it => it.LastUpDateTime).ValueGeneratedOnAddOrUpdate();
            entityTypeBuilder.Property(it => it.IsDeleted).HasDefaultValue(false);
            entityTypeBuilder.HasQueryFilter(it => it.IsDeleted == false);//不可以写成 it => !it.IsDeleted
            return entityTypeBuilder;
        }
    }
}
